const { Controller } = require('egg')

const createRule = {
	title: 'string',
	path: 'string',
	icon: 'string',
}
/**
 * @controller Menu 菜单
 */
class MenuController extends Controller {
	/**
	 * @summary 菜单列表
	 * @description 菜单列表
	 * @router get /admin/menu
	 */
	async index() {
		const ctx = this.ctx
		try {
			const { username } = ctx.decode
			const data = await ctx.service.menu.index(username)
			if (data.status === 'success') {
				ctx.helper.success(data.data)
			} else {
				ctx.helper.error(data)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}
	/**
	 * @summary 添加菜单
	 * @description 添加菜单
	 * @router post /admin/menu
	 * @request body createMenuRequest
	 */
	async create() {
		const ctx = this.ctx
		try {
			ctx.validate(createRule, ctx.request.body)
			const status = await ctx.service.menu.create(ctx.request.body)
			if (status === 'success') {
				ctx.helper.success('创建成功')
			} else {
				ctx.helper.error(status)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}
	/**
	 * @summary 更新菜单
	 * @description 更新菜单
	 * @router put /admin/menu/{id}
	 * @request path string *id 标识
	 * @request body createMenuRequest
	 */
	async update() {
		const ctx = this.ctx
		try {
			ctx.validate(createRule, ctx.request.body)
			const { id } = ctx.params
			const status = await ctx.service.menu.update(id, ctx.request.body)
			if (status === 'success') {
				ctx.helper.success('更新成功')
			} else {
				ctx.helper.error(status)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}

	/**
	 * @summary 查看菜单详情
	 * @description 查看菜单详情
	 * @router get /admin/menu/{id}
	 * @request path string *id 标识
	 */
	async show() {
		const ctx = this.ctx
		try {
			const { id } = ctx.params
			const data = await ctx.service.menu.show(id, ctx.request.body)
			if (data.status === 'success') {
				ctx.helper.success(data.data)
			} else {
				ctx.helper.error(data)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}
}

module.exports = MenuController
